package dfbz.线程锁3;

import java.util.concurrent.locks.ReentrantLock;

/*
 * 解决线程安全问题：
 *   1、使用lock接口的实现类创建锁对象
 *       lock接口中成员方法：
 *           lock()  获取锁
 *           unlock() 释放锁
 *

 * */
public class RunnableImpl implements Runnable {
    //票的总数
    private static Integer ticket=100;
    //定义锁对象
    private static Object obj=new Object();

    //使用lock的实现类创建锁对象
    ReentrantLock lock=new ReentrantLock();

    @Override
    public void run() {
        while (true){
            //获取锁
            lock.lock();
            if (ticket>0){
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    System.out.println(111);
                    //释放锁
                    lock.unlock();
                }
                //打印当前卖出的票
                System.out.println(Thread.currentThread().getName() + "正在卖第: " + ticket + "张票");
                //票数减1
                ticket--;
            }

        }
    }
}
